﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PTUDW_CNTN2010_F_CDT.Models;
using PTUDW_CNTN2010_F_CDT.Filters;

namespace PTUDW_CNTN2010_F_CDT.Controllers
{
    [LanguageFilter]
    public class ShoppingCartController : Controller
    {
        EcommerceDBContext db = new EcommerceDBContext();

        public ActionResult ViewCart()
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);

            var viewModel = new ViewCartModel
            {
                CartItems = cart.GetCartItems(),
                CartTotal = cart.GetTotal(),
            };

            return View(viewModel);
        }

        [HttpPost]
        public ActionResult RemoveFromCart(int id)
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);

            string productName = db.Carts.Single(item => item.RecordId == id).Product.ProductName;

            int itemCount = cart.RemoveProductFromCart(id);

            var results = new CartRemoveViewModel
            {
                Message = Server.HtmlEncode(productName) + " has been removed from your shopping cart.",
                CartTotal = cart.GetTotal(),
                CartCount = cart.GetCount(),
                ItemCount = itemCount,
                DeleteId = id
            };

            return Json(results);
        }

        [ChildActionOnly]
        public ActionResult GetSumaryCart()
        {
            var shoppingCart = ShoppingCart.GetCart(this.HttpContext);

            ViewBag.SumCart = shoppingCart.GetCount();
            return PartialView();
        }

        [HttpPost]
        public int AddToCart(int id)
        {
            var product = db.Products
                .Single(p => p.ProductId == id);
            var cart = ShoppingCart.GetCart(this.HttpContext);

            cart.AddProductToCart(product);

            return cart.GetCount();
        }
    }
}
